package xnj.lazydog.btcontroller;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;



import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import xnj.lazydog.btcontroller.Constant;

public class ReportService extends IntentService {

    public static long startTime = 0;

    public static void uploadUsage(Context context)
    {

        OkHttpClient client = new OkHttpClient();
        String brand = Build.BRAND;
        String model = Build.MODEL;
        String phoneVer = Build.VERSION.RELEASE;
        String appVerCode ,appVerName;
        String appName;
        PackageManager manager = context.getPackageManager();
        appName = context.getApplicationInfo().packageName;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            appVerCode = ""+info.versionCode;
            appVerName = info.versionName;
        }catch (PackageManager.NameNotFoundException e)
        {
            appVerCode = "null";
            appVerName = "null";
            e.printStackTrace();
        }

        long sec = (System.currentTimeMillis() - startTime)/1000;
        Log.w(TAG, "uploadUsage: "+startTime +"  "+ System.currentTimeMillis());

        RequestBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("brand",brand)
                .addFormDataPart("model",model+"-OS"+phoneVer)
                .addFormDataPart("app_name",appName)
                .addFormDataPart("ver_name",appVerName)
                .addFormDataPart("duration", ""+sec)
                .build();
        Request request = new Request.Builder()
                .url(Constant.USAGE_REPORT_URL) // 上传地址
                .post(body)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 文件上传成功
                if (response.isSuccessful()) {
                    Log.w(TAG, "onResponse: " + response.body().string());
                } else {
                    Log.w(TAG, "onResponse: " + response.message());
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                // 文件上传失败
                Log.w(TAG, "onFailure: " + e.getMessage());
            }
        });

    }


    // 使用OkHttp上传文件
    public static void uploadFile(Context context, File file) {

        OkHttpClient client = new OkHttpClient();
        MediaType contentType = MediaType.parse("text/plain"); // 上传文件的Content-Type

        String deviceID = Build.ID;
        String brand = Build.BRAND;
        String model = Build.MODEL;
        String device = Build.DEVICE;
        String phoneVer = Build.VERSION.RELEASE;
        String appVerCode ,appVerName;
        String appName;
        PackageManager manager = context.getPackageManager();
        appName = context.getApplicationInfo().packageName;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            appVerCode = ""+info.versionCode;
            appVerName = info.versionName;
        }catch (PackageManager.NameNotFoundException e)
        {
            appVerCode = "null";
            appVerName = "null";
            e.printStackTrace();
        }
        //RequestBody body = RequestBody.create(contentType, file); // 上传文件的请求体
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)

                .addFormDataPart("file", file.getName(),
                        RequestBody.create(MediaType.parse("multipart/form-data"), file))
                .addFormDataPart("device_id",deviceID)
                .addFormDataPart("brand",brand)
                .addFormDataPart("model",model)
                .addFormDataPart("device",device)
                .addFormDataPart("os_ver",phoneVer)
                .addFormDataPart("app_ver_code",appVerCode)
                .addFormDataPart("app_ver_name",appVerName)
                .addFormDataPart("app_name",appName)
                .build();

        Request request = new Request.Builder()
                .url(Constant.ERR_REPORT_URL) // 上传地址
                .post(requestBody)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 文件上传成功
                if (response.isSuccessful()) {
                    Log.w(TAG, "onResponse: " + response.body().string());
                } else {
                    Log.w(TAG, "onResponse: " + response.message());
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                // 文件上传失败
                Log.w(TAG, "onFailure: " + e.getMessage());
            }
        });
        Log.w(TAG, "uploadFile: " );
    }

    public void checkAndReportError()
    {


        File dir = getApplicationContext().getExternalFilesDir("log");
        if(dir!=null&&!dir.exists())
            if(!dir.mkdir())
            {
                Log.w(TAG, "saveErrorLog: make dir failed");
                return;
            }

        File file = new File(dir,"log.txt");
        if(file.exists())
        {
            Log.w(TAG, "checkAndReportError: error" );
            uploadFile(this, file);
        }else
        {
            Log.w(TAG, "checkAndReportError: no error" );
        }
    }

    private static final String TAG = "ReportService";

    public ReportService(String name)
    {
        super(name);

    }

    public ReportService()
    {

        super("re");

        startTime = System.currentTimeMillis();
    }


    @Override
    public int onStartCommand( Intent intent, int flags, int startId) {
        startTime = System.currentTimeMillis();
        Log.w(TAG, "onStartCommand: "+startTime );
        //Log.w(TAG, "onStartCommand: " );
        checkAndReportError();
        return super.onStartCommand(intent, flags, startId);
    }


    @Override
    public void onDestroy() {
        //android.os.Process.killProcess(android.os.Process.myPid());
        super.onDestroy();
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

    }
}
